'''
Created on 15/10/2011

@author: Digao
'''

import re
def toInt(arg):
    return int(arg)

def toStr(a,b):
    return str(a)+' '+str(b)

def traverse(node):
    if not node:
        return
    print str(node.value)+":"+str(node.prob)
    traverse(node.yes)
    traverse(node.no)
    

class Node():
    def __init__(self,val,prob):
        self.yes=None
        self.no=None
        self.value=val
        self.prob=prob
    
    def __repr__(self):
        return str(self.value)+":"+str(self.prob)

number_re = re.compile(r'[\s\.\d]+')
feat_re = re.compile(r'[a-zA-Z]+')

def parse(nodes):
    parents=[]
    i=0
    while i < len(nodes):
        node=nodes[i]
        last_parent=None
        if parents:
            last_parent=parents[-1]
            if not last_parent.yes:
                last_parent.yes=node
            elif not last_parent.no:
                last_parent.no=node
                parents.pop()
        if node.value:
            parents.append(node)
        i+=1
    return nodes[0]
    


def parse_tree(L):
    lines = []
    for i in range(L):
        lines.append(input.readline().strip())
    tree_exp = ' '.join(lines)
    tree_exp = tree_exp.replace('(',' ').replace(')',' ')
    tok_str = tree_exp.strip().split()
    nodes=[]
    for tok in tok_str:
        if number_re.match(tok):
            nodes.append(Node(None, float(tok)))
        elif feat_re.match(tok):
            nodes[-1].value=tok
    tree = parse(nodes)
    return tree
    
def evaluate(toks,root):
    animal = toks[0]
    feats = {}
    for i in xrange(2,int(toks[1])+2):
        feats[toks[i]]=1
    node = root
    result=1
    while node:
        result = result*node.prob
        if node.value in feats:
            node=node.yes
        else:
            node=node.no
    print '%.7f'%result


input = open('input.in')
CASES = int(input.readline())
for case in range(1,CASES+1):
    L = int(input.readline())
    root = parse_tree(L)
    print 'Case #%d:'%case
    A = int(input.readline())
    for _ in xrange(A):
        evaluate(input.readline().strip().split(),root)
    
    


